<template>
  <div>
    <el-dialog
      :title="title"
      :width="dialogWidth"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="visible"
      :before-close="BeforeClose"
      top="1vh"
    >
      <el-form
        v-if="visible"
        :model="inputForm"
        ref="inputForm"
        :rules="rules"
        v-loading="loading"
        :class="method==='view'?'readonly':''"
        :disabled="method==='view'"
      >
        <el-row :gutter="15">
          <div>
            <el-collapse
              v-model="activeName"
              @change="haChange"
            >
              <el-collapse-item
                title="创建模板"
                name="1"
                disabled
              >
                <el-col :span="12">
                  <el-form-item
                    label="类型名称:"
                    prop="templateType"
                    label-width="120px"
                  >
                    <el-select
                      style="width: 100%;"
                      v-model="inputForm.templateType"
                      :disabled="method=='continue'"
                      placeholder="请选择"
                      clearable
                    >
                      <el-option
                        v-for="item in contractTypeList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>


                <el-col :span="12">

                  <el-form-item
                    label-width="120px"
                    label="模板名称:"
                    prop="templateName"
                  >
                    <el-input
                      v-model="inputForm.templateName"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col
                  :span="12"
                >
                  <!--action="https://jsonplaceholder.typicode.com/posts/"  /config/sysuploadfile/upload:headers="headers"-->
                  <el-form-item
                    label="附件上传:"
                    label-width="120px"
                    prop="templateLocation"
                  >
                    <el-upload
                      class="upload-demo"
                      ref="upload"
                      :headers="headers"
                      action=""
                      multiple
                      :limit="5"
                      :data="filedata"
                      :on-remove="handleRemove"
                      :on-success="onFileSuccess"
                      :file-list="fileList"
                      :http-request="handleChanged"
                    >
                      <el-button
                        type="primary"
                        icon="el-icon-upload2"
                      >上传文件</el-button>
                      <div
                        slot="tip"
                        class="el-upload__tip"
                      >支持扩展名：.rar .zip .doc .docx .pdf .jpg...</div>
                    </el-upload>
                  </el-form-item>

                </el-col>
              </el-collapse-item>
            </el-collapse>
          </div>
        </el-row>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          @click="BeforeClose"
          icon="el-icon-circle-close"
        >取 消</el-button>
        <el-button
          type="primary"
          icon="el-icon-circle-check"
          v-if="method != 'view'"
          @click="doSubmit()"
        >提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  tableMarketOption
} from '@/const/crud/market/contractTemplate/person'
import {
  getObj,
  addObj,
  editObj,
  putObj,
  uploadFile,
} from '@/api/market/contractTemplate/person'
import {
  getDicType
} from '@/api/common'
import store from "@/store"
import {
  getStore
} from '@/util/store'
//import { getStore } from '../util/store'

export default {
  data () {
    return {
      state1: '',
      title: '',
      dialogWidth: '50%',
      page: {
        //current: 1, // 当前页数
        size: -1 // 每页显示多少条
      },
      method: '',
      headers: {
        Authorization: 'Bearer ' + store.getters.access_token,
        tenantId: 0
      },
      filedata: {
        remarks: '',
        uploadPath: 'user/path'
      },
      file: null,
      visible: false,
      loading: false,
      contractTypeList: [],
      fileList: [],
      fileLists: [],
      activeName: ['1', '2', '3'],
      inputForm: {
        id: '',
        templateType : '',
        templateName: '',
        templateLocation: '',
      },

      // 表单校验
      rules: {
        templateType: [{
          required: true,
          message: "类型名称不能为空",
          trigger: "blur"
        }],
        templateName: [{
          required: true,
          message: "模板名称不能为空",
          trigger: "blur"
        }],
        // templateLocation: [{
        //   required: true,
        //   message: "模板附件不能为空",
        //   trigger: "blur"
        // }],
      },
    }
  },
  created () {
    this.headers.tenantId = getStore({
      name: 'tenantId'
    })
  },
  methods: {
    BeforeClose () {
      this.visible = false
      if (this.$refs.inputForm) {
        this.$refs.inputForm.resetFields()
        this.$refs.inputForm.clearValidate()
      }
    },
    test (value, callback) {
      if (value) {
        value = value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')
      }
      if (callback) {
        callback()
      }
      return value
    },
    tests (value) {
      if (value) {
        value = value.replace(/[^\d]/g, '')
      }
      return value
    },

    // 多图片上传
    handleChanged (raw) {
      this.fileLists.push(raw.file);
      // this.fileList = raw
      console.log(raw.file)
      let formdata = new FormData()
      formdata.append('file', raw.file);
      uploadFile(formdata).then(data => {
        console.log(data)
        this.$message.success('添加成功')
        this.inputForm.templateLocation = data.data.result.url
      })
    },

    //获取附件数据
    getFile () {
      //获取文件方法
      getFileList().then(response => {
        if (response.data != null) {
          this.tableFileData = response.data.data.records;
        }
      });
    },

    haChange (val) {
      // console.log(val);
    },
    handleRemove (file, fileList) {
      let removeIndex = -1
      this.fileLists.forEach((item, index) => {
        if (item.name == file.name) {
          removeIndex = index
        }
      })
      if (removeIndex >= 0) {
        this.fileLists.splice(removeIndex, 1)
      }
      console.log(this.fileLists)
      this.inputForm.templateLocation = ''
    },
    //上传成功
    onFileSuccess (response, file, fileList) {
      var that = this;
      if (response.data != null) {
        var fileArry = {
          fileId: ''
        };
        response.data = (response.data || '') + '';
        fileArry.fileId = response.data;
        that.ctContractFileLists.push(fileArry);
      }
    },
    //上传文件
    handleChange (file, fileList) {
      this.fileList = fileList.slice(-3);
    },
    init (method, id) {
      this.visible = true
      // setTimeout(() => {
      this.inputForm.contractTypeId = ''
      this.fileList = []
      this.fileLists = []
      this.method = method
      this.inputForm.id = id
      if (method === 'add') {
        this.title = `新建合同`
      } else if (method === 'edit') {
        this.title = '修改合同'
      } else if (method === 'view') {
        this.title = '查看合同'
      } else if (method === 'continue') {
        this.title = '续租合同'
        this.isChangeDate = false
      }
      
      this.loading = false
      this.$nextTick(() => {
        getDicType('contract_type').then(res => {
        	this.contractTypeList = res.data.data
        })
        if (this.$refs.inputForm) {
          this.$refs.inputForm.clearValidate()
        }
        if (method === 'add' || method === 'edit' ) {
          this.inputForm = this.$options.data().inputForm
        }
        if (method === 'edit' || method === 'view' || method === 'continue') { // 修改或者查看
          getObj(id).then(response => {
            this.inputForm = response.data.data;
          })
        }

      })
      // }, 5)
    },
    // 手动校验
    ischceked (value) {
      if (value) {
        return false
      } else {
        return true
      }
    },
    // 表单提交
    doSubmit () {
      this.$refs['inputForm'].validate((valid) => {
        if (valid) {
          if (this.inputForm.id) {
            editObj(this.inputForm).then(data => {
              this.$message.success('修改成功')
              this.$emit('refreshDataList')
              this.BeforeClose()
            });
          } else {
            addObj(this.inputForm).then(data => {
              this.$message.success('添加成功')
              this.$emit('refreshDataList')
              this.BeforeClose()
            })
          }
        }
      })
    },

    handleSelect (item) {
      console.log(item);
    },

  }
}
</script>
<style lang="scss" scoped>
/deep/.el-collapse-item__content {
  display: flex;
  flex-wrap: wrap;
}
</style>
